import asyncio
import turtle
import queue
import threading
import time
import json
import sys
import os
import re
import mcp
from mcp.server.fastmcp import FastMCP
from typing import List, Tuple, Union

# Initialize FastMCP server
mcp = FastMCP("Drawing")

screen = None
pens = {}


def _get_pen(color: str) -> turtle.Turtle:
    """获取或创建指定颜色的画笔"""
    global pens
    if color not in pens:
        pen = turtle.Turtle()
        pen.speed(0)  # 最快速度
        pen.hideturtle()
        pen.color(color)
        pens[color] = pen
    return pens[color]


def parse_points_string(s: str) -> list[tuple[float, float]]:
    """
    解析形如 "[(x1,y1), (x2,y2), (x3,y3)]" 的字符串为元组列表
    
    Args:
        s: 输入字符串，格式为 "[(x1,y1), (x2,y2), (x3,y3)]"
        
    Returns:
        包含3个元组的列表，每个元组包含两个浮点数
        
    Raises:
        ValueError: 如果字符串格式不正确或无法解析
    """
    # 使用正则表达式匹配所有数字
    numbers = re.findall(r'-?\d+\.?\d*', s)
    
    if len(numbers) != 6:
        raise ValueError("字符串中应该包含6个数字")
    
    try:
        # 将字符串转换为浮点数
        numbers = [float(n) for n in numbers]
        
        # 创建三个元组
        points = [
            (numbers[0], numbers[1]),
            (numbers[2], numbers[3]),
            (numbers[4], numbers[5])
        ]
        
        return points
    except ValueError as e:
        raise ValueError(f"无法将字符串转换为数字: {e}")





@mcp.tool()
async def draw_triangle(points: str, fill_color: str) -> dict:
    """
    绘制三角形
    
    Args:
        points: 三个点的坐标列表，格式为 [(x1,y1), (x2,y2), (x3,y3)]
        fill_color: 填充颜色名称
        
    Returns:
        dict: 操作状态
    """
    global screen
    try:

        pts = parse_points_string(points)

        # if len(points) != 3:
        #     return {"status": "error", "message": "需要三个点来绘制三角形" + type(points)}
        
        pen = _get_pen(fill_color)
        pen.penup()
        pen.goto(pts[0])
        pen.pendown()
        pen.begin_fill()
        pen.goto(pts[1])
        pen.goto(pts[2])
        pen.goto(pts[0])
        pen.end_fill()
        
        screen.update()
        return {"status": "success"}
    except Exception as e:
        return {"status": "error", "message": str(e) + "\n需要三个点来绘制三角形。形式为：[(x1,y1),(x2,y2),(x3,y3)] 。"}

@mcp.tool()
async def draw_rectangle(position: List[float], fill_color: str) -> dict:
    """
    绘制矩形
    
    Args:
        position: 矩形的位置和尺寸 [left, top, width, height]
        fill_color: 填充颜色名称
        
    Returns:
        dict: 操作状态
    """
    global screen
    try:
        if len(position) != 4:
            return {"status": "error", "message": "需要四个参数 [left, top, width, height]"}
        
        left, top, width, height = position
        pen = _get_pen(fill_color)
        pen.penup()
        pen.goto(left, top)
        pen.pendown()
        pen.begin_fill()
        pen.forward(width)
        pen.right(90)
        pen.forward(height)
        pen.right(90)
        pen.forward(width)
        pen.right(90)
        pen.forward(height)
        pen.end_fill()
        
        screen.update()
        return {"status": "success"}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
async def draw_circle(params: List[float], fill_color: str) -> dict:
    """
    绘制圆形
    
    Args:
        params: 包含圆心和半径的列表 [centerx, centery, radius]
        fill_color: 填充颜色名称
        
    Returns:
        dict: 操作状态
    """
    global screen, running
    try:
        if len(params) != 3:
            return {"status": "error", "message": "需要三个参数 [centerx, centery, radius]"}
        
        centerx, centery, radius = params
        pen = _get_pen(fill_color)
        pen.penup()
        pen.goto(centerx, centery - radius)
        pen.pendown()
        pen.begin_fill()
        pen.circle(radius)
        pen.end_fill()
        
        screen.update()
        return {"status": "success"}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
async def clear_canvas() -> dict:
    """
    清除画布上的所有图形
    
    Returns:
        dict: 操作状态
    """
    global screen, running
    try:
        screen.clear()
        # pens.clear()  # 清除画笔缓存
        screen.update()
        return {"status": "success"}
    except Exception as e:
        return {"status": "error", "message": str(e)}



# @mcp.tool()
async def run():
    global screen, running
    while running:
        screen.update()  # 更新画面
        await asyncio.sleep(0.01)  # 让出控制权给事件循环


if __name__ == "__main__":
    screen = turtle.Screen()
    screen.setup(800, 600)
    # screen.tracer(0)  # 关闭自动更新以提高性能
    running = True
    mcp.run(transport='stdio')
